<template>
<div>
  <el-row :gutter="20">
    <el-col :span="8">

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>个人信息</span>
        </div>
        <div style="display: flex;justify-content:center; flex-direction: column;align-items: center">
          <el-upload
              :headers="headers"
               name="avatarfile"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-error="handleAvatarError"
              :action="BASE_API+'dev-api/system/user/profile/avatar'"
              class="avatar-uploader"
          >
            <img v-if="userinfo.user.avatar" :src="userinfo.user.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
            <div class="mask">
              <i class="el-icon-plus"></i>
            </div>
          </el-upload>
          <el-divider></el-divider>
          <div class="profile">
            <div><i class="el-icon-user-solid"></i>用户名称</div>
            <div>{{userinfo.user.userName}}</div>
          </div>
          <el-divider></el-divider>
          <div class="profile">
            <div><i class="el-icon-mobile-phone"></i>手机号码</div>
            <div>{{userinfo.user.phonenumber}}</div>
          </div>
          <el-divider></el-divider>
          <div class="profile">
            <div><i class="el-icon-message"></i>用户邮箱</div>
            <div>{{userinfo.user.email}}</div>
          </div>
          <el-divider></el-divider>
          <div class="profile">
            <div><i class="el-icon-message"></i>创建日期</div>
            <div>{{userinfo.user.createTime}}</div>
          </div>
        </div>
      </el-card>

    </el-col>
    <el-col :span="16">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>个人信息</span>
        </div>
        <el-tabs v-model="activeName">
          <el-tab-pane label="基本资料" name="first">
          <el-form ref="editForm" :model="userinfo.user" :rules="rules" label-width="80px">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="userinfo.user.nickName" maxlength="30" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="userinfo.user.phonenumber" maxlength="11" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userinfo.user.email" maxlength="50" />
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="userinfo.user.sex">
                <el-radio label="0">男</el-radio>
                <el-radio label="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submit">保存</el-button>
              <el-button type="danger" @click="close">关闭</el-button>
            </el-form-item>
          </el-form>
          </el-tab-pane>

          <el-tab-pane label="修改密码" name="second">
            <el-form ref="pwdRef" :model="user" :rules="rules" label-width="80px">
              <el-form-item label="旧密码" prop="oldPassword">
                <el-input v-model="user.oldPassword" placeholder="请输入旧密码" type="password" show-password />
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="user.newPassword" placeholder="请输入新密码" type="password" show-password />
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input v-model="user.confirmPassword" placeholder="请确认新密码" type="password" show-password />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitPassword">保存</el-button>
                <el-button type="danger" @click="close">关闭</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="第三方应用" name="third">
            TODO
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-col>
  </el-row>
</div>
</template>

<script>
import {getToken} from "@/utils/auth";
import {getUserInfo} from "@/api/home";
import {updateUserProfile,updateUserPwd} from "@/api/userInfo";


const token=getToken()

export default {

  name: "UserInfo",
  data() {
    return{
      userinfo:{
        user:{
          userName:'',
          avatar:'',
          nickName:'',
          email:'',
          phonenumber:'',
          createTime:'',
          sex:''
        }
      },
      imgUrl:'',
      headers:{
        'Authorization': 'Bearer '+token,
        'clientid':'209ef407810e3856f40870a9f0e769d7'
      },
      BASE_API: 'http://localhost/',
      activeName: 'first',
      user:{
        oldPassword: "",
        newPassword: "",
        confirmPassword: ""
      }
    }
  },
  mounted() {
    this.getUserInfo()
  },
  methods:{
    //获取用户信息
    getUserInfo(){
      getUserInfo().then(res=>{
        this.userinfo=res.data
      })
    },
    // 上传成功回调
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        this.imgUrl = res.data.imgUrl
        // 强制重新渲染
        this.$forceUpdate()
        this.$notify({
          title: 'EasyCTBA',
          message: '头像上传成功！',
          type: 'success',
          duration: '2000',
          offset: 100
        });
      } else {
        this.$notify({
          title: 'EasyCTBA',
          message: res.msg,
          type: 'error',
          duration: '2000',
          offset: 100
        });
      }
    },
    // 错误处理
    handleAvatarError(res) {
      this.$notify({
        title: 'EasyCTBA',
        message: res.msg,
        type: 'error',
        duration: '2000',
        offset: 100
      });
    },
    // 上传校验
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isLt2M) {
        this.$notify({
          title: 'EasyCTBA',
          message: '上传头像图片大小不能超过2MB',
          type: 'error',
          duration: '2000',
          offset: 100
        });
      }
      return isLt2M
    },
    //提交修改
    submit(){
      this.$refs.editForm.validate(valid => {
        if (valid) {
          updateUserProfile(this.userinfo.user).then(()=>{
            this.$notify({
              title: 'EasyCTBA',
              message: '修改成功！',
              type: 'success',
              duration: '2000',
              offset: 100
            });
          })
        }
      });
    },
    //修改密码
    submitPassword() {
      this.$refs.pwdRef.validate(valid => {
        if (valid) {
          updateUserPwd(this.user.oldPassword, this.user.newPassword).then(() => {
            this.$notify({
              title: 'EasyCTBA',
              message: '修改成功！',
              type: 'success',
              duration: '2000',
              offset: 100
            });
          })
        }
      })
    },
    close(){
      this.$router.go(-1);
    }
  },
  computed:{
    rules(){
      const equalToPassword = (rule, value, callback) => {
        if (this.user.newPassword !== value) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      };
      return{
        nickName: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
        email: [{ required: true, message: "邮箱地址不能为空", trigger: "blur" }, {
          type: "email",
          message: "请输入正确的邮箱地址",
          trigger: ["blur", "change"]
        }],
        phonenumber: [{
          required: true,
          message: "手机号码不能为空",
          trigger: "blur"
        }, { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],

        oldPassword: [{ required: true, message: "旧密码不能为空", trigger: "blur" }],
        newPassword: [{ required: true, message: "新密码不能为空", trigger: "blur" }, {
          min: 6,
          max: 20,
          message: "长度在 6 到 20 个字符",
          trigger: "blur"
        }],
        confirmPassword: [{ required: true, message: "确认密码不能为空", trigger: "blur" }, {
          required: true,
          validator: equalToPassword,
          trigger: "blur"
        }]
      }
    }
  }
}
</script>

<style scoped>
.box-card{
  border-radius: 10px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px #8C93AA dotted;
  border-radius: 50%;
}
.avatar {
  width: 100%;
  height: 100%;
  display: block;
  border-radius: 50%;
}
.avatar-uploader{
  position: relative;
  display: inline-block;
  width: 178px;
  height: 178px;
}
.mask{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.4);
  border-radius: 50%;
  color: #ffffff;
  justify-content: center;
  align-items: center;
  display: none;
}
.avatar-uploader:hover .mask{
  display: flex;
}
.profile{
  display: flex;
  width: 100%;
  justify-content: space-between;
}
</style>